package com.lean.android.ad.repository

import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.lean.android.ad.duration.DurationManager
import com.lean.android.ad.utils.AdLog
import com.lean.android.network.Result
import kotlinx.coroutines.launch

internal object ReportHelper {

    fun String?.toCpmInt(): Int {
        return if (this.isNullOrEmpty()) 0
        else {
            this.toFloat().toInt()
        }
    }

    enum class AdPositionType(val posId: Int, val posName: String) {
        ReSplash(-1, "reSplash"), Splash(1, "splash"), RewardVideo(2, "reward"), Interstitial(
            3, "insert"
        ),
        Feed(4, "feed"), Full(5, "full"),
    }

    enum class AdEventType(val eventType: Int, val eventTypeName: String) {
        AdLoaded(1, "填充"), AdShowed(3, "曝光"), AdError(2, "无填充")
    }

    private val appScope by lazy {
        ProcessLifecycleOwner.get().lifecycleScope
    }

    /**
     * 广告事件上报
     */
    fun reportAdEvent(
        requestId: String,
        eventType: AdEventType,
        platformId: String = "-1",
        adPosition: AdPositionType,
        cpm: Int = 0,
        errorCode: String = "0"
    ) {
        appScope.launch {
            AdLog.d(
                AdLog.AdReportTag,
                "广告事件[${eventType.eventTypeName}]上报开始，参数：\n requestId: $requestId, platform $platformId, adPosition ${adPosition.posName}, cpm $cpm , errorCode $errorCode"
            )
            val result = Repositories.adRepository.reportAdEvent(
                requestId, eventType, platformId, adPosition, cpm, errorCode
            )
            when (result) {
                is Result.Success -> {
                    AdLog.d(
                        AdLog.AdReportTag,
                        "广告事件[${eventType.eventTypeName}]上报成功！参数： \n requestId: $requestId, platform $platformId, adPosition ${adPosition.posName}, cpm $cpm , errorCode $errorCode"
                    )
                }

                is Result.Error -> {
                    AdLog.e(
                        AdLog.AdReportTag,
                        "广告事件[${eventType.eventTypeName}]上报失败。 code:${result.error.errorCode}, message ${result.error.errorMessage}"
                    )
                }

                else -> {

                }
            }
        }

    }

    suspend fun reportAppDuration(duration: Long) {
        AdLog.d(AdLog.AdReportTag, "开始上报使用时长！ duration: $duration ms.")
        val result = Repositories.adRepository.reportAppDuration(duration)
        when (result) {
            is Result.Success -> {
                DurationManager.clearAppDuration()
                AdLog.d(AdLog.AdReportTag, "开始上报使用时长成功， duration: $duration ms.")
            }

            is Result.Error -> {
                AdLog.d(AdLog.AdReportTag, "开始上报使用时长失败， duration: $duration ms.")
            }

            else -> {}
        }
    }

}